﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace carXapp2.FuncPages
{
    public partial class AddEditReminder : PhoneApplicationPage
    {
        private string reminderID;
        private string CarID;
        public AddEditReminder()
        {
            InitializeComponent();
            this.DataContext = App.ViewModel.SingleReminder;
        }

        private void menuSave_click(object sender, EventArgs e)
        {
            bool success = false;
            if (reminderID == null)
            { success = AddRecord(int.Parse(CarID)); }
            else
            {
                success = UpdateRecord();
            }

            if (NavigationService.CanGoBack && success)
            { NavigationService.GoBack(); }
       }

        private bool AddRecord(int id)
        {
            int miles;
            var rs1 = int.TryParse(txtmiles.Text, out miles);
            if (rs1)
            {
                App.ViewModel.SingleReminder.CarID = int.Parse(CarID);
                App.ViewModel.SingleReminder.DateStr = txtdate1.Value.Value.ToShortDateString();
                App.ViewModel.AddReminder(App.ViewModel.SingleReminder);
                return true;
            }
            else
            {
                MessageBox.Show("Incorrect or Incomplete data");
                return false;
            }

        }

        private bool UpdateRecord()
        {
           int miles;
            var rs1 = int.TryParse(txtmiles.Text, out miles);
            if (rs1)
            {
                App.ViewModel.SingleReminder.DateStr = txtdate1.Value.Value.ToShortDateString();
                App.ViewModel.SaveChangesToDB();
                return true;
            }
            else
            {
                MessageBox.Show("Incorrect or Incomplete data");
                return false;
            }

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            
            NavigationContext.QueryString.TryGetValue("ReminderID", out reminderID);
            NavigationContext.QueryString.TryGetValue("CarID", out CarID);
            base.OnNavigatedTo(e);
        }
    }
}